package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.DepartmentLogic;
import com.hotel.BL.HouseKeepingUserLogic;
import com.hotel.BL.UserLevelLogic;
import com.hotel.BL.UserLogic;
import com.hotel.BL.UserMappingHotelLogic;

import data.Department;
import data.HouseKeepingUser;
import data.User;
import data.UserMappingHotel;
import data.passingData.ResultData;
import data.passingData.UserData4Admin;


@SuppressWarnings("serial")
public class UserService extends HttpServlet {
	
	//http://localhost:8080/userService?func=GetStaff&department=HouseKeeping
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String func = req.getParameter("func");
			if(func.equals("GetStaff")){
				GetStaff(req,resp);
			}else if(func.equals("getDepartmentAndUserLevel")){
				GetDepartmentAndUserLevel(req,resp);
			}else if(func.equals("getAll4Admin")){
				GetAll4Admin(req,resp);
			}else if(func.equals("changeStatus")){
				ChangeStatus(req,resp);
			}else if(func.equals("del")){
				DeleteUserMapping(req,resp);
			}else if(func.equals("add")){
				AddUser(req,resp);
			}else if(func.equals("edit")){
				EditUser(req,resp);
			}else if(func.equals("getById")){
				GetUserById(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void GetStaff(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{	
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		if(session.getAttribute("hotelId") != null)
			hotelId = (Long)session.getAttribute("hotelId");
		
		DepartmentLogic deptLogic = new DepartmentLogic();
		String department = req.getParameter("department");
		Department dept = deptLogic.GetDepartment(hotelId, department);
		Gson gson = new Gson();
		if(!dept.getTitle().equals("HouseKeeping")){
			List<User> task = new UserLogic(req,resp).GetUserFromDepartment(hotelId, dept.getId());
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(task));
		}else{
			List<HouseKeepingUser> houseKeepingList = new HouseKeepingUserLogic(req, resp).GetAllHouseKeepingUser(hotelId);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(houseKeepingList));
		}
		
		
		
	}
	
	private void GetDepartmentAndUserLevel(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
				
		Gson gson = new Gson();
		
		HashMap<String,Object> data = new HashMap<String,Object>();
		DepartmentLogic dLogic = new DepartmentLogic();
		UserLevelLogic uLogic = new UserLevelLogic(req, resp);
		data.put("Department",dLogic.OnlyIdAndTitle(dLogic.GetAllDepartment(hotelId)));
		data.put("UserLevel",uLogic.OnlyIdAndTitle(uLogic.GetAllUserLevel4Admin(hotelId)));
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void GetAll4Admin(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		
		List<UserData4Admin> obj = new UserLogic(req, resp).GetAllUser4AdminLimit(hotelId,offset,line);
		double dataSize = new UserMappingHotelLogic(req, resp).GetAllUser4Admin(hotelId).size();
		
		Gson gson = new Gson();
		
		HashMap<String,Object> data = new HashMap<String,Object>();
		data.put("dataAmount",dataSize);
		data.put("pageNumber",pointer);
		data.put("lineAmount", line);
		data.put("pageAmount", Math.ceil(dataSize/line));
		data.put("data", obj);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long id = Long.parseLong(req.getParameter("id"));

		Object obj = new UserMappingHotelLogic(req,resp).ChangeStatus(id);

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void DeleteUserMapping(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String id = req.getParameter("id");
		UserMappingHotelLogic logic = new UserMappingHotelLogic(req, resp);
		for(int i = 0; i < id.split(",").length ; i++){
			logic.DeleteUserMappingHotel(Long.parseLong(id.split(",")[i]));
		}

		GetAll4Admin(req, resp);
	}
	
	private void AddUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		long hotelId = (Long) session.getAttribute("hotelId");
		String address = req.getParameter("address");
		Date birthday = formatter.parse(req.getParameter("birthday"));
		String bloodGroup = req.getParameter("bloodGroup");
		String city = req.getParameter("city");
		String country = req.getParameter("country");
		Date dateOfJoin = formatter.parse(req.getParameter("dateOfJoin"));
		String designation = req.getParameter("designation");
		String driverLicense = req.getParameter("driverLicense");
		String emergencyNumber = req.getParameter("emergencyNumber");
		String firstName = req.getParameter("firstName");
		String gender = req.getParameter("gender");
		String identificationNo = req.getParameter("identificationNo");
		String lastName = req.getParameter("lastName");
		String mobile = req.getParameter("mobile");
		String passportNumber = req.getParameter("passportNumber");
		String phone = req.getParameter("phone");
		String socialSecurityCard = req.getParameter("socialSecurityCard");
		String state = req.getParameter("state");
		String zipCode = req.getParameter("zipCode");
		String department = req.getParameter("department");
		String userlevel = req.getParameter("userlevel");
		String email = req.getParameter("email");
		String pass = req.getParameter("pass");
		User u =new UserLogic(req, resp).Add(hotelId,address,birthday,bloodGroup,
				city,country,dateOfJoin,designation,driverLicense,emergencyNumber,firstName,
				gender,identificationNo,lastName,mobile,passportNumber,phone,
				socialSecurityCard,state,zipCode,email,pass);
		new UserMappingHotelLogic(req, resp).AddUserMapping(hotelId, String.valueOf(u.getId()),department, userlevel);
		GetAll4Admin(req, resp);
	}

	private void EditUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException, ParseException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		long hotelId = (Long) session.getAttribute("hotelId");
		long id = Long.parseLong(req.getParameter("id"));
		String address = req.getParameter("address");
		Date birthday = formatter.parse(req.getParameter("birthday"));
		String bloodGroup = req.getParameter("bloodGroup");
		String city = req.getParameter("city");
		String country = req.getParameter("country");
		Date dateOfJoin = formatter.parse(req.getParameter("dateOfJoin"));
		String designation = req.getParameter("designation");
		String driverLicense = req.getParameter("driverLicense");
		String emergencyNumber = req.getParameter("emergencyNumber");
		String firstName = req.getParameter("firstName");
		String gender = req.getParameter("gender");
		String identificationNo = req.getParameter("identificationNo");
		String lastName = req.getParameter("lastName");
		String mobile = req.getParameter("mobile");
		String passportNumber = req.getParameter("passportNumber");
		String phone = req.getParameter("phone");
		String socialSecurityCard = req.getParameter("socialSecurityCard");
		String state = req.getParameter("state");
		String zipCode = req.getParameter("zipCode");
		String department = req.getParameter("department");
		String userlevel = req.getParameter("userlevel");
		String email = req.getParameter("email");
		String pass = req.getParameter("pass");
		User u =new UserLogic(req, resp).Edit(id,address,birthday,bloodGroup,
				city,country,dateOfJoin,designation,driverLicense,emergencyNumber,firstName,
				gender,identificationNo,lastName,mobile,passportNumber,phone,
				socialSecurityCard,state,zipCode,email,pass);
		UserMappingHotel m = new UserMappingHotelLogic(req, resp).GetUserMapping(hotelId, String.valueOf(u.getId()));
		m.setDepartmentString(department);
		m.setUserlevelString(userlevel);
		new UserMappingHotelLogic(req, resp).UpdateUserMappingHotel(m);
		GetAll4Admin(req, resp);
	}
	
	private void GetUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		long id = Long.parseLong(req.getParameter("id"));
		User u = new UserLogic(req, resp).GetUser(id);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(new UserLogic(req, resp).ToUserData4AdminEdit(u)));
	}
}
